package com.itheima.web.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.Category;
import com.itheima.domain.Route;
import com.itheima.factory.BeanFactory;
import com.itheima.service.CategoryService;
import com.itheima.service.RouteService;
import com.itheima.service.impl.CategoryServiceImpl;
import com.itheima.service.impl.RouteServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/routeServlet")
public class RouteServlet extends BaseServlet {
    private RouteService routeService = (RouteService) BeanFactory.getBean("routeService");

    private void findRouteByCid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String cid = request.getParameter("cid");
        List<Route> routeList = routeService.findRouteByCid(Integer.parseInt(cid));
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(routeList);
        response.getWriter().write(json);
    }

    private void findRouteDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String rid = request.getParameter("rid");
        Route route = routeService.findRouteByRid(Integer.parseInt(rid));
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(route);
        response.getWriter().write(json);
    }

    private void findByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String cid = request.getParameter("cid");
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        PageInfo<Route> pageInfo = routeService.findByPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize), Integer.parseInt(cid));
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(pageInfo);
        response.getWriter().write(json);
    }

}
